package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"hello/inits/config"
	"log"
)

var DB *gorm.DB

func BootstrapDB() *gorm.DB {
	fmt.Println("数据库初始化开始")
	source := GetDbSource()
	//原来，全局变量是需要直接使用=号，而不能使用:=的，之后再做实验todo
	var err error
	DB, err = gorm.Open(mysql.Open(source), &gorm.Config{})
	if err != nil {
		fmt.Println(source)
		log.Fatal("数据库初始化配置出错:", err)
	}
	fmt.Println("DB1:地址:")
	fmt.Println(DB)
	return DB
}

func GetDbSource() string {
	var dataSource = "%s:%s@tcp(%s:%s)/%s?charset=utf8"
	username := config.GetString("DB_USERNAME")
	password := config.GetString("DB_PASSWORD")
	database := config.GetString("DB_DATABASE")
	host := config.GetString("DB_HOST")
	port := config.GetString("DB_PORT")
	source := fmt.Sprintf(dataSource, username, password, host, port, database) + "&loc=Asia%2FShanghai"
	return source
}
